﻿using Abp.Dependency;
using Abp.Runtime.Validation;
using Microsoft.AspNetCore.Http;
using NLog;
using System;
using System.Threading.Tasks;

namespace Batman.Cms.Core.Middlewares
{
    public class ExceptionHandlingMiddleware
    {
        private readonly RequestDelegate _next;

        private Logger _logger;

        public ExceptionHandlingMiddleware()
        {
            _logger = IocManager.Instance.Resolve<Logger>();
        }

        public ExceptionHandlingMiddleware(RequestDelegate next) : this()
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (AbpValidationException ex)
            {
                var statusCode = context.Response.StatusCode;
                await HandleExceptionAsync(context, ex.ToString());
            }
            catch (Exception ex)
            {
                var statusCode = context.Response.StatusCode;
                await HandleExceptionAsync(context, ex.ToString());
            }
        }
        private Task HandleExceptionAsync(HttpContext context, string msg)
        {
            _logger.Error(msg);
            return context.Response.WriteAsync("ERROR:" + msg);
        }
    }
}
